// src/router/index.js
import { createRouter, createWebHistory } from 'vue-router'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login/index.vue'),
    meta: { 
      title: '登录',
      requiresAuth: false 
    }
  },
  {
    path: '/',
    name: 'Layout',
    component: () => import('@/views/layout/index.vue'),
    redirect: '/dashboard',
    meta: { 
      requiresAuth: true 
    },
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/dashboard/index.vue'),
        meta: { 
          title: '数据看板',
          requiresAuth: true
        }
      },
      {
        path: 'system/user',
        name: 'UserManagement',
        component: () => import('@/views/system/user/index.vue'),
        meta: { 
          title: '用户管理',
          requiresAuth: true
        }
      },
      {
        path: 'business/product',
        name: 'ProductManagement',
        component: () => import('@/views/business/product/index.vue'),
        meta: { 
          title: '产品管理',
          requiresAuth: true
        }
      },
      {
        path: 'business/order',
        name: 'OrderManagement',
        component: () => import('@/views/business/order/index.vue'),
        meta: { 
          title: '订单管理',
          requiresAuth: true
        }
      }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/'
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 直接从 localStorage 获取 token，避免在路由守卫中使用 store
  const token = localStorage.getItem('admin_token')
  
  console.log('路由导航:', to.path, 'Token:', token)
  
  // 设置页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - Easy Go 后台管理系统`
  }
  
  // 如果前往登录页且已登录，重定向到首页
  if (to.path === '/login' && token) {
    next('/')
    return
  }
  
  // 如果需要认证但未登录，重定向到登录页
  if (to.meta.requiresAuth && !token) {
    next('/login')
    return
  }
  
  next()
})

export default router